package com.example.proxy.cglibproxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 对没有实现任何接口的类，使用cglib进行代理
 */
public class CGLIBProxy {
    public CGLIBProxy(){}
    Object obj;
    public Object bind(final Object target)
    {
        this.obj = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(obj.getClass());
        enhancer.setCallback(new MethodInterceptor() {
                                 @Override
                                 public Object intercept(Object obj, Method method, Object[] args,
                                                         MethodProxy proxy) throws Throwable
                                 {
                                     System.out.println("CGLIBPROXY  一些代码");
                                     Object res = method.invoke(target, args);
                                     return res;
                                 }
                             }
        );
        return enhancer.create();
    }
}
